package com.example.mydy.manager;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.mydy.model.Achievement;
import com.example.mydy.utils.MockDataManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 成就管理类，负责管理用户成就
 */
public class AchievementManager {
    private static final String TAG = "AchievementManager";
    private static final String PREFS_NAME = "achievements_prefs";

    private static AchievementManager instance;
    private Context context;
    private List<Achievement> achievements;

    // 私有构造函数
    private AchievementManager(Context context) {
        this.context = context.getApplicationContext();
        this.achievements = new ArrayList<>();
        initAchievements();
    }

    /**
     * 获取AchievementManager单例实例
     * @param context 上下文
     * @return AchievementManager实例
     */
    public static synchronized AchievementManager getInstance(Context context) {
        if (instance == null) {
            instance = new AchievementManager(context);
        }
        return instance;
    }

    /**
     * 初始化成就列表
     */
    private void initAchievements() {
        // 登录类成就
        achievements.add(new Achievement("1", "初次登录", "首次登录应用", Achievement.TYPE_LOGIN, Achievement.LEVEL_BRONZE, 1, 1.0));
        achievements.add(new Achievement("2", "常客", "累计登录7天", Achievement.TYPE_LOGIN, Achievement.LEVEL_BRONZE, 7, 5.0));
        achievements.add(new Achievement("3", "忠实用户", "累计登录30天", Achievement.TYPE_LOGIN, Achievement.LEVEL_SILVER, 30, 20.0));
        achievements.add(new Achievement("4", "超级粉丝", "累计登录100天", Achievement.TYPE_LOGIN, Achievement.LEVEL_GOLD, 100, 50.0));

        // 任务类成就
        achievements.add(new Achievement("5", "初试身手", "完成第一个任务", Achievement.TYPE_TASK, Achievement.LEVEL_BRONZE, 1, 2.0));
        achievements.add(new Achievement("6", "任务达人", "完成10个任务", Achievement.TYPE_TASK, Achievement.LEVEL_BRONZE, 10, 10.0));
        achievements.add(new Achievement("7", "任务专家", "完成50个任务", Achievement.TYPE_TASK, Achievement.LEVEL_SILVER, 50, 30.0));
        achievements.add(new Achievement("8", "任务王者", "完成100个任务", Achievement.TYPE_TASK, Achievement.LEVEL_GOLD, 100, 80.0));

        // 社交类成就
        achievements.add(new Achievement("9", "社交新手", "邀请第一个好友", Achievement.TYPE_SOCIAL, Achievement.LEVEL_BRONZE, 1, 5.0));
        achievements.add(new Achievement("10", "人脉达人", "邀请10个好友", Achievement.TYPE_SOCIAL, Achievement.LEVEL_SILVER, 10, 30.0));
        achievements.add(new Achievement("11", "社交达人", "拥有3级下线", Achievement.TYPE_SOCIAL, Achievement.LEVEL_GOLD, 3, 100.0));

        // 收益类成就
        achievements.add(new Achievement("12", "初次收益", "首次获得收益", Achievement.TYPE_INCOME, Achievement.LEVEL_BRONZE, 1, 1.0));
        achievements.add(new Achievement("13", "小康生活", "累计收益达到100元", Achievement.TYPE_INCOME, Achievement.LEVEL_SILVER, 100, 10.0));
        achievements.add(new Achievement("14", "财富自由", "累计收益达到1000元", Achievement.TYPE_INCOME, Achievement.LEVEL_GOLD, 1000, 50.0));
        achievements.add(new Achievement("15", "收益大亨", "累计收益达到10000元", Achievement.TYPE_INCOME, Achievement.LEVEL_DIAMOND, 10000, 200.0));

        // 从SharedPreferences加载已保存的成就状态
        loadAchievementStates();
    }

    /**
     * 从SharedPreferences加载成就状态
     */
    private void loadAchievementStates() {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        for (Achievement achievement : achievements) {
            String id = achievement.getId();
            int currentValue = prefs.getInt("achievement_" + id + "_current", 0);
            boolean unlocked = prefs.getBoolean("achievement_" + id + "_unlocked", false);
            long unlockTime = prefs.getLong("achievement_" + id + "_unlock_time", 0);

            achievement.setCurrentValue(currentValue);
            achievement.setUnlocked(unlocked);
            achievement.setUnlockTime(unlockTime);
        }
    }

    /**
     * 保存成就状态到SharedPreferences
     */
    private void saveAchievementState(Achievement achievement) {
        SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit();
        String id = achievement.getId();
        editor.putInt("achievement_" + id + "_current", achievement.getCurrentValue());
        editor.putBoolean("achievement_" + id + "_unlocked", achievement.isUnlocked());
        editor.putLong("achievement_" + id + "_unlock_time", achievement.getUnlockTime());
        editor.apply();
    }

    /**
     * 更新成就进度
     * @param achievementId 成就ID
     * @param increment 增量值
     * @return 如果成就刚解锁返回true，否则返回false
     */
    public boolean updateAchievementProgress(String achievementId, int increment) {
        for (Achievement achievement : achievements) {
            if (achievement.getId().equals(achievementId)) {
                boolean wasUnlocked = achievement.isUnlocked();
                achievement.setCurrentValue(achievement.getCurrentValue() + increment);
                
                if (!wasUnlocked && achievement.isUnlocked()) {
                    // 成就刚解锁，设置解锁时间
                    achievement.setUnlockTime(System.currentTimeMillis());
                    
                    // 保存状态
                    saveAchievementState(achievement);
                    return true;
                }
                
                // 保存状态
                saveAchievementState(achievement);
                return false;
            }
        }
        return false;
    }

    /**
     * 检查所有成就的完成状态
     * @param username 用户名
     */
    public void checkAllAchievements(String username) {
        MockDataManager mockDataManager = MockDataManager.getInstance();
        
        // 检查登录成就 (这里只是示例，实际应该根据登录记录检查)
        updateAchievementProgress("1", 1); // 初次登录
        
        // 检查任务相关成就
        int completedTaskCount = mockDataManager.getCompletedTaskCount(username);
        for (Achievement achievement : achievements) {
            if (achievement.getType() == Achievement.TYPE_TASK) {
                achievement.setCurrentValue(completedTaskCount);
                saveAchievementState(achievement);
            }
        }
        
        // 检查社交成就
        int downlineCount = mockDataManager.getTotalDownlineUsersCount(username);
        for (Achievement achievement : achievements) {
            if (achievement.getType() == Achievement.TYPE_SOCIAL && 
                    (achievement.getId().equals("9") || achievement.getId().equals("10"))) {
                achievement.setCurrentValue(downlineCount);
                saveAchievementState(achievement);
            }
        }
        
        // 检查收益成就
        double totalIncome = mockDataManager.getTotalDownlineIncome(username);
        for (Achievement achievement : achievements) {
            if (achievement.getType() == Achievement.TYPE_INCOME) {
                achievement.setCurrentValue((int)totalIncome);
                saveAchievementState(achievement);
            }
        }
    }

    /**
     * 获取所有成就
     * @return 所有成就列表
     */
    public List<Achievement> getAllAchievements() {
        return new ArrayList<>(achievements);
    }

    /**
     * 根据类型获取成就
     * @param type 成就类型
     * @return 指定类型的成就列表
     */
    public List<Achievement> getAchievementsByType(int type) {
        if (type == Achievement.TYPE_ALL) {
            return getAllAchievements();
        }
        
        List<Achievement> filteredAchievements = new ArrayList<>();
        for (Achievement achievement : achievements) {
            if (achievement.getType() == type) {
                filteredAchievements.add(achievement);
            }
        }
        return filteredAchievements;
    }

    /**
     * 获取成就总数
     * @return 成就总数
     */
    public int getTotalAchievementsCount() {
        return achievements.size();
    }

    /**
     * 获取已解锁成就数量
     * @return 已解锁成就数量
     */
    public int getUnlockedAchievementsCount() {
        int count = 0;
        for (Achievement achievement : achievements) {
            if (achievement.isUnlocked()) {
                count++;
            }
        }
        return count;
    }

    /**
     * 根据ID获取成就
     * @param achievementId 成就ID
     * @return 成就对象，如果不存在返回null
     */
    public Achievement getAchievementById(String achievementId) {
        for (Achievement achievement : achievements) {
            if (achievement.getId().equals(achievementId)) {
                return achievement;
            }
        }
        return null;
    }
} 